﻿using Microsoft.Practices.Unity;

namespace MvvmFx.Common.ViewModels.Behaviors.LoadingSaving
{
    /// <summary>
    /// Abstract base class for ViewModelLoader objects.
    /// Creats an instance of a ViewModel class and populates with the data from the model.
    /// </summary>
    public abstract class ViewModelLoader<T> : IViewModelLoader<T> where T : ILoadSaveable
    {
        #region Constructor

        protected ViewModelLoader(IUnityContainer container)
        {
            this.Container = container;
        }

        #endregion

        #region properties

        /// <summary>
        /// Dependency container to be used for DI by child classes.
        /// </summary>
        protected IUnityContainer Container
        {
            get;
            private set;
        }

        #endregion

        #region Public methods

        /// <summary>
        /// Loads an existing ViewModel object with data from the model.
        /// </summary>
        /// <param name="viewModel"></param>
        public void Load(T viewModel)
        {
            OnLoad(viewModel);

            // Mark the page as being UnModified
            viewModel.ChangeService.MarkUnmodified();
        }

        #endregion

        #region Protected methods

        /// <summary>
        /// Override in derived classes to load an existing ViewModel object.
        /// </summary>
        /// <param name="viewModel"></param>
        protected abstract void OnLoad(T viewModel);

        #endregion

        #region IViewModelLoader Members

        void IViewModelLoader.Load(ILoadSaveable viewModel)
        {
            Load((T)viewModel);
        }

        #endregion
    }
}